/**
 *
 */
package top.jle.wx.proxy.config;


import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import feign.RequestInterceptor;
import feign.codec.ErrorDecoder;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import top.jle.jpa.basic.exception.BasicCustomException;
import top.jle.wx.proxy.interceptor.GlobalInterceptor;
import top.jle.wx.proxy.util.GlobalThreadLocalUtil;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author jim.lee
 *
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

	private static final Logger LOGGER = LoggerFactory.getLogger(WebConfig.class);
	private static final long MAX_AGE = 24 * 60 * 60L;

	@Autowired
	private GlobalInterceptor globalInterceptor;

	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")
				//是否发送Cookie
				.allowCredentials(true)
				//放行哪些原始域
				.allowedOriginPatterns("*")
				.allowedMethods("*")
				.allowedHeaders("*")
				.exposedHeaders("*");
	}

	@Bean
	public InternalResourceViewResolver internalResourceViewResolver() {
		return new InternalResourceViewResolver();
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(globalInterceptor).excludePathPatterns("/swagger**/**","/**/api-docs/**","/oauth/OauthUserInfo","/oauth/OauthSNSBase","/redPacket/**");
	}

	@Override
	public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
		FastJsonHttpMessageConverter fc = new FastJsonHttpMessageConverter();
		fc.setDefaultCharset(StandardCharsets.UTF_8);
		fc.getFastJsonConfig().setWriterFeatures(JSONWriter.Feature.WriteLongAsString,JSONWriter.Feature.WriteEnumsUsingName,JSONWriter.Feature.WriteNullStringAsEmpty,JSONWriter.Feature.WriteMapNullValue,JSONWriter.Feature.WriteNullListAsEmpty, JSONWriter.Feature.PrettyFormat);
		converters.add(0,fc);
		converters.add(new ResourceHttpMessageConverter());
		converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
	}

	@Bean
	public RequestInterceptor requestInterceptor(){
		return (requestTemplate)->{
			String url = requestTemplate.request().url();
			if(!url.contains("/cgi-bin/token?grant_type=client_credential") && !url.contains("/sns/userinfo?lang=zh_CN") && !url.contains("/sns/jscode2session")){
				requestTemplate.query("access_token", GlobalThreadLocalUtil.getAccessToken());
			}else if(url.contains("sns/jscode2session")){
				requestTemplate.query("appid",GlobalThreadLocalUtil.getAppId());
				requestTemplate.query("secret",GlobalThreadLocalUtil.getSecret());
			}
		};
	}



	@Bean
	public ErrorDecoder errorDecoder(){
		return (methodKey, response) -> {

			BasicCustomException exception = new BasicCustomException(String.valueOf(response.status()));

			try {
				String body = IOUtils.toString(response.body().asInputStream(),"utf-8");
				JSONObject json = JSONObject.parseObject(body);
				if(json!=null && json.containsKey("code")){
					exception = new BasicCustomException(json.getString("code"));
				}
			} catch (IOException e) {
				LOGGER.error(e.getMessage(),e);
			}
			return exception;
		};
	}



}
